import { from, Observable, of, Subject, BehaviorSubject, observable } from 'rxjs';
export class WebSocketUtil {

    //链接地址
    private url: string;
    //websocket对象
    private _websocket: any;
    // 返回对象
    websocketObj = {
        send: null,
        get: null,
        websocket: null
    }

    constructor() {

    }

    /**获取websocket对象 */
    async getWebsocket(url: string) {
        this.url = url;
        let o= await this.open().then(res=>{
            return res;
        }).catch(err=>{
            return err;
        });
        this.get();
        this.websocketObj.websocket = this._websocket;
        if(o=='open'){
            return this.websocketObj;
        }else{
            return null;
        }
    }

    /**打开链接 */
    open() {
        const self = this;
        return new Promise((resolve, reject) => {
            self._websocket = new WebSocket(self.url);
            self._websocket.onopen = (e) => {
                this.websocketObj.send = new BehaviorSubject(null);
                self.websocketObj.send.subscribe(data => {
                    self._websocket.send(JSON.stringify(data));
                });
                resolve(e.type);
            };
            self._websocket.onerror = (e) => {
                reject(e.type);
            }
            self._websocket.onclose = (e) => {
                reject(e.type);
            }
        });
    }

    /**获取 */
    get() {
        const self = this;
        self.websocketObj.get = new Observable(
            observer => {
                // 一旦websocket有数据推送过来，Observable立马弹出数据
                self._websocket.onmessage = (event) => {
                    observer.next(JSON.parse(event.data));
                };

                return function unsubscribe() {
                    self._websocket.close();
                    console.log('Close WebSocket.');
                };
            }
        );
    }

}